import React, { useRef } from "react";
import  {ProTable, ActionType } from "@ant-design/pro-components";
import { Badge, Button, message, Popconfirm, Space, Tag } from "antd";
import Detail from "./component/Detail";
import { useRequest } from "ahooks";
import {
  evaluationV1AdminControllerIndex,
  evaluationV1AdminControllerUpdateEvaluationArticle
} from "@/services/auto/evaluationAdmin";
import { completeImgUrl } from "common/utils/utils";
import { BooleanNumber, evaluationCategory, EvaluationCategory, EvaluationStatus } from "common/utils/data";
import { green, orange, blue } from '@ant-design/colors';
import { VerticalAlignTopOutlined } from "@ant-design/icons";
import { Radio } from "antd";
import Add from "./component/Add";
import { specificationV1AdminControllerAll } from "@/services/auto/specificationAdmin";
import { brandV1AdminControllerIndex } from "@/services/auto/brandAdmin";

export default function EvaluationData(){
  const actionRef = useRef<ActionType>();

  const {runAsync: patchRun} = useRequest(evaluationV1AdminControllerUpdateEvaluationArticle,{
    manual: true,
    
    onSuccess: ()=>{
      actionRef.current?.reload();
      message.success('操作成功');
    }
  })

  const {
    data: presetSpecifications,
  } = useRequest(()=>specificationV1AdminControllerAll({}));

  return <ProTable<
      API.EvaluationAdminIndexResult,
      Omit<API.EvaluationV1AdminControllerIndexParams, 'brandUuids'> & {brandUuids?: string[]}
    >
    actionRef={actionRef}
    rowKey="uuid"
    options={false}
    pagination={{
      showSizeChanger: true,
      showTotal: (total: number, [start, end]: [number, number]) =>
        `第 ${start}-${end} 条/总共 ${total} 条`,
    }}
    toolBarRender={() => [
    ...(presetSpecifications ? [
        <Button href={`/api/v1/admin/evaluations/export-raw-fr-data?__token=${localStorage['token'] ?? ''}`} key="export" target="_blank">
          导出所有耳机频响数据
        </Button>,
        <Add key="add" presetSpecifications={presetSpecifications} reload={()=>{
          actionRef.current?.reload();
        }}>
          <Button type="primary">
            添加评测数据
          </Button>
        </Add>
      ] : [])
    ]}
    request={(param) => {
      const {
        pageSize,
        current,
        title,
        status,
        brandUuids,
      } = param;
      return evaluationV1AdminControllerIndex({
        title,
        status,
        brandUuids: brandUuids?.join(','),
        pageSize,
        pageIndex: current,
      }).then((res) => {
        return {
          success: true,
          data: res.list,
          total: res.total
        };
      });
    }}
    columns={[
      {
        align: 'center',
        title: '缩略图',
        dataIndex: 'thumbnails',
        width: 120,
        render: (val, record) => {
          return (
            record.article.thumbnails?.length ? <a
              href={completeImgUrl(record.article.thumbnails[0])}
              target="_blank"
              className="flex justify-center"
              style={{ textAlign: 'center' }}
            >
              <img src={completeImgUrl(record.article.thumbnails[0])} alt="图片" className="w-full" />
            </a> : '--'
          );
        },
        hideInSearch: true,
      },
      {
        align: 'center',
        title: '品牌',
        key: 'brandUuids',
        renderText: (val, record)=>{
          return record.brand.title;
        },
        fieldProps: {
          showSearch: true,
          optionFilterProp: 'label',
          mode: 'multiple',
        },
        valueType: 'select',
        request: ()=>{
          return brandV1AdminControllerIndex({
            pageSize: 9999,
            enableTitleSort: BooleanNumber.true,
          }).then(res=>{
            return res.list.map(item=>{
              return {
                label: item.title,
                value: item.uuid,
              }
            })
          })
        }
      },
      {
        align: 'center',
        title: '标题',
        dataIndex: 'title',
        render: (val, record) => {
          return (
            <Badge
              count={
                <Popconfirm
                  title={record.article.isStick ? '取消当前置顶吗？' : '确认当前置顶吗？'}
                  okText="确定"
                  cancelText="取消"
                  onConfirm={() => {
                    patchRun(
                      {uuid: record.uuid},
                      { isStick: record.article.isStick === 1 ? 0 : 1 },
                    );
                  }}
                >
                  <VerticalAlignTopOutlined
                    style={{
                      color: record.article.isStick ? blue.primary : 'initial',
                      fontSize: '18px',
                      cursor: 'pointer',
                    }}
                    title={record.article.isStick ? '置顶中' : '未置顶'}
                  />
                </Popconfirm>
              }
            >
              {val}
            </Badge>
          );
        },
      },
      {
        align: 'center',
        title: '状态',
        dataIndex: 'status',
        render: (val) => {
          return (
            <Tag
              color={val === EvaluationStatus.PUBLISH ? green.primary : orange.primary}
            >
              {val === EvaluationStatus.PUBLISH ? '已发布' : '未发布'}
            </Tag>
          );
        },
        renderFormItem: () => {
          return (
            <Radio.Group
              defaultValue=""
              buttonStyle="solid"
            >
              <Radio.Button value="">全部</Radio.Button>
              <Radio.Button value="UNPUBLISH">未发布</Radio.Button>
              <Radio.Button value="PUBLISH">已发布</Radio.Button>
            </Radio.Group>
          );
        },
      },
      {
        align: 'center',
        title: '分类',
        key: 'category',
        hideInSearch: true,
        renderText: (val, record) => {
          return evaluationCategory[record.category as EvaluationCategory];
        },
      },
      {
        align: 'center',
        title: '关键词',
        key: 'keywords',
        hideInSearch: true,
        render: (val, record) => {
          return record.article.keywords?.length ? record.article.keywords.map((item, index) => <Tag key={index}>{item}</Tag>) : '-';
        },
      },
      {
        align: 'center',
        title: '最新发布时间',
        dataIndex: ['article', 'publishTime'],
        hideInSearch: true,
        valueType: 'dateTime',
      },
      {
        align: 'center',
        title: '描述',
        dataIndex: ['article', 'desc'],
        hideInSearch: true,
        ellipsis: true,
      },
      {
        align: 'center',
        title: '操作',
        dataIndex: 'option',
        valueType: 'option',
        width: 300,
        render: (_, record) => (
          <Space direction="vertical" size={0}>
            <Detail data={record} reload={actionRef.current?.reload}>
              <Button type="link">
                详情
              </Button>
            </Detail>
            {presetSpecifications && <Add data={record} presetSpecifications={presetSpecifications} reload={() => {
              actionRef.current?.reload();
            }}>
              <Button type="link">
                编辑
              </Button>
            </Add>}
            {/*<Button
              type="link"
              onClick={() => {
                window.open(history.createHref({
                  pathname: '/carousel',
                  search: `?articleUuid=${record.uuid}`,
                }));
              }}
            >
              设置为轮播
            </Button>*/}
          </Space>
        ),
      },
    ]}
  />
}
